package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.nursing.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @version 1.0
 * @description 说明
 * @package com.zzyl.nursing.service.impl
 */
@Service
@Slf4j
public class WechatServiceImpl implements WechatService {


    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";


    @Value("${wechat.appId}")
    private String appid;

    @Value("${wechat.appSecret}")
    private String secret;

    /**
     * 通过code获取openId
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        HashMap<String,Object> params = new HashMap<String,Object>();
        params.put("appid", appid);
        params.put("secret", secret);
        // 前端中code参数
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        HttpResponse response = HttpUtil.createGet(REQUEST_URL).form(params).timeout(30000).execute();
        if (response.isOk()) {//响应成功
            //响应回来数据
            String jsonString = response.body();
            //解析json字符串，获取指定的json中的key, jsonObject另种map
            //JSONObject jsonObject = JSONUtil.parseObj(jsonString);
            /*Object object = jsonObject.get("openid");
            String openId = (String) object;*/
            String openId = JSONUtil.parseObj(jsonString).getStr("openid");
            log.info("openId: {}", openId);
            if(StrUtil.isNotEmpty(openId)){
                return openId;
            }
        }
        //报错
        throw new ServiceException("获取openId失败!");
    }

    /**
     * 获取微信授权
     * @return
     */
    public String getAccessToken(){
        HashMap<String,Object> params = new HashMap<String,Object>();
        params.put("appid", appid);
        params.put("secret", secret);
        params.put("grant_type", "client_credential");
        HttpResponse response = HttpUtil.createGet(TOKEN_URL).form(params).timeout(30000).execute();
        if (response.isOk()) {//响应成功
            //响应回来数据
            String jsonString = response.body();
            String access_token = JSONUtil.parseObj(jsonString).getStr("access_token");
            log.info("access_token: {}", access_token);
            if(StrUtil.isNotEmpty(access_token)){
                return access_token;
            }
        }
        //报错
        throw new ServiceException("获取微信授权失败!");
    }

    /**
     * 获取用户的手机号码
     *
     * @param phoneCode
     * @return
     */
    @Override
    public String getPhoneNumber(String phoneCode) {
        String url = PHONE_REQUEST_URL + getAccessToken();
        HashMap<String,Object> params = new HashMap<String,Object>();
        //前端传过来的phoneCode
        params.put("code", phoneCode);
        HttpResponse response = HttpUtil.createPost(url).body(JSONUtil.toJsonStr(params)).timeout(30000)
            .execute();
        if (response.isOk()) {
            String jsonString = response.body();
            log.info("获取手机号码返回结果: {}", jsonString);
            String phoneNumber = JSONUtil.parseObj(jsonString).getByPath("phone_info.purePhoneNumber", String.class);
            if(StrUtil.isNotEmpty(phoneNumber)){
                return phoneNumber;
            }
        }
        throw new ServiceException("获取手机号码失败!");
    }
}
